<?php

class ProductController extends BackEndController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array(
                'allow',
                'actions' => array('login', 'logout'),
                'users' => array('*'),
            ),
            array(
                'allow',
                'actions' => array('index', 'view', 'create', 'update', 'admin', 'delete'),
                'users' => array('@'),
                'expression' => 'Yii::app()->user->isAdmin() == "true" || Yii::app()->user->isEditor() == "true"',
            ),

            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionCreate() {
        $model = new Product;

        $categories = Category::model()->findAll(array(
            'select' => 'cat_id, cat_name',
            'condition' => 'parent_id > 0',
        ));
        $methods = BuyMethod::model()->findAll();
        $locations = TreTodayCommon::getArrayCityOfVietNam();

        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];
            $model->product_code = TreTodayCommon::getSEO($model->product_name);
            $model->website = $_POST['Product']['website'];
            $model->nick_ym = $_POST['Product']['nick_ym'];
            $model->nick_skype = $_POST['Product']['nick_skype'];
            $model->status = $_POST['Product']['status'];

            $category = Category::model()->findByPk($model->cat_id);
            $model->cat_code = $category == null ? "" : TreTodayCommon::getSEO($category->cat_name);
            $model->views = 0;
            $model->add_time = time();
            $model->modify_time = time();
            if (Yii::app()->user == null || Yii::app()->user->id == 0) {
                $model->user_id = 0;
                $model->user_name = '';
            } else {
                $user = UserBack::model()->findByPk(Yii::app()->user->id);
                $model->user_id = Yii::app()->user->id;
                $model->user_name = $user->user_name;
            }

            //handle image
            $file = CUploadedFile::getInstance($model, 'image');
            if ($file != null) {
                $imageVariables = getimagesize($file->tempName);
                $file = EUploadedImage::getInstance($model, 'image');
                $arr_size = TreTodayCommon::getResizeImage($imageVariables[0], $imageVariables[1]);
                $file->maxWidth = $arr_size['width'];
                $file->maxHeight = $arr_size['height'];
                $rnd = rand(0, 999999);
                $fileName = "{$rnd}.jpg";
                $base = TreTodayCommon::createFolder('products');
                $base = $base . '/' . $fileName;
                if ($file->saveAs($base)) {
                    $img = new Image();
                    $img->image_path = TreTodayCommon::generateImagePath('products', $fileName);
                    $img->save();

                    $model->image_id = $img->image_id;
                    if ($model->save()) {
                        $this->redirect(array('index'));
                    }
                }
            }
        }

        $this->render('create', array(
            'model' => $model,
            'categories' => $categories,
            'methods' => $methods,
            'locations' => $locations
        ));
    }

    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        $categories = Category::model()->findAll(array(
            'select' => 'cat_id, cat_name',
            'condition' => 'parent_id > 0',
        ));
        $methods = BuyMethod::model()->findAll();
        $locations = TreTodayCommon::getArrayCityOfVietNam();
        $img = Image::model()->findByPk($model->image_id);
        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];
            $model->product_code = TreTodayCommon::getSEO($model->product_name);
            $model->nick_ym = $_POST['Product']['nick_ym'];
            $model->nick_skype = $_POST['Product']['nick_skype'];
            $model->website = $_POST['Product']['website'];
            $model->status = $_POST['Product']['status'];

            $category = Category::model()->findByPk($model->cat_id);
            $model->cat_code = $category == null ? "" : TreTodayCommon::getSEO($category->cat_name);
            $model->views = 0;
            $model->add_time = time();
            $model->modify_time = time();
//            if (Yii::app()->user == null || Yii::app()->user->id == 0) {
//                $model->user_id = 0;
//                $model->user_name = '';
//            } else {
//                $user = UserBack::model()->findByPk(Yii::app()->user->id);
//                $model->user_id = Yii::app()->user->id;
//                $model->user_name = $user->user_name;
//            }

            //handle image
            $file = CUploadedFile::getInstance($model, 'image');

            if ($file != null) {
                $imageVariables = getimagesize($file->tempName);
                $file = EUploadedImage::getInstance($model, 'image');
                $arr_size = TreTodayCommon::getResizeImage($imageVariables[0], $imageVariables[1]);
                $file->maxWidth = $arr_size['width'];
                $file->maxHeight = $arr_size['height'];
                $rnd = rand(0, 999999);
                $fileName = "{$rnd}.jpg";
                $base = TreTodayCommon::createFolder('products');
                $base = $base . '/' . $fileName;
                if ($file->saveAs($base)) {
                    $img = Image::model()->findByPk($model->image_id);
                    if ($img != null) {
                        $img->image_path = $img->image_path = TreTodayCommon::generateImagePath('products', $fileName);
                        $img->save();
                    }
                }
            }
            if ($model->save()) {
                $this->redirect(array('index'));
            }
        }

        $this->render('update', array(
            'model' => $model,
            'categories' => $categories,
            'methods' => $methods,
            'locations' => $locations,
            'image' => $img
        ));
    }

    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
    }

    public function actionIndex() {
        if (isset($_GET['published']) && $_GET['published'] == 0) {
            $published = false;
        } else {
            $published = true;
        }
        if ($published) {
            $model = new Product('search');
            $model->unsetAttributes(); // clear any default values
            if (isset($_GET['Product']))
                $model->attributes = $_GET['Product'];
            return $this->render('admin', array(
                'model' => $model,
            ));
        } else {
            $model = Product::model()->getForGridBackend($published);
            return $this->render('notShow', array(
                'model' => $model,
            ));
        }
//        $model = new Product('search');
//        $model->unsetAttributes(); // clear any default values
//        if (isset($_GET['Product']))
//            $model->attributes = $_GET['Product'];
//
//        $this->render('admin', array(
//            'model' => $model,
//        ));

//        return $this->render('admin', array(
//            'model' => $model,
//        ));
    }

    public function loadModel($id) {
        $model = Product::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function actionLogin() {
        $this->redirect(TreTodayUrl::backendLoginUrl());
    }

    public function actionLogout() {
        $this->redirect(TreTodayUrl::backendLogoutUrl());
    }

}
